package com.czk.doc;

import com.czk.util.ClientUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * 组合查询
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/14 17:38
 */
public class CombineQuery {
    public static void main(String[] args) throws IOException {
        // 客户端
        RestHighLevelClient highLevelClient = ClientUtil.getHighLevelClient();
        // 组合查询
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 设置组合插叙你条件
        boolQueryBuilder.must(QueryBuilders.matchQuery("age", "2"));
        // address
        boolQueryBuilder.must(QueryBuilders.matchQuery("address", "河北"));
        searchSourceBuilder.query(boolQueryBuilder);
        // 查询
        searchRequest.indices("stack").source(searchSourceBuilder);
        // 查询
        SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsString());
        }
        highLevelClient.close();
    }
}
